package locks.dead;

import locks.entity.Account;
import locks.entity.DollarAmount;
import locks.exception.InsufficientFundsException;

public class DynamicSequenceDeadLock {

    /**
     * 锁的顺序取决于 传入的参数顺序,所以存在死锁
     * @param fromAccount
     * @param toAccount
     * @param amount
     * @throws InsufficientFundsException
     */
    public static void transferMoney(Account fromAccount,
                                     Account toAccount,
                                     DollarAmount amount)
            throws InsufficientFundsException {
        synchronized (fromAccount) {
            synchronized (toAccount) {
                //账户余额大于O
                if (fromAccount.getBalance().compareTo(amount) < 0)
                    throw new InsufficientFundsException();
                else {
                    //转账
                    fromAccount.debit(amount);
                    toAccount.credit(amount);
                }
            }
        }
    }
}
